import { useUserStore } from "@/store";

type HttpMethod = "GET" | "POST" | "PUT" | "DELETE";

const request = (url : string, method : HttpMethod, data : any = {}) => {
	const userStore = useUserStore();
	const token = userStore.token;

	// 判断是否是登录接口
	const isLoginRequest = url.includes('/login');

	return new Promise((resolve, reject) => {
		uni.request({
			url: 'http://localhost:8080/app' + url,
			method, // 请求方法
			data, // 请求数据
			header: {
				// 只有在请求不是登录接口时，才添加 token
				Authorization: !isLoginRequest && token ? `Bearer ${token}` : '',
			},
			timeout: 5000, // 请求超时时间
			success: (res) => {
				if (res.statusCode === 200) {
					resolve(res.data); // 成功回调
				} else {
					// 处理非 200 状态码的响应
					if (res.statusCode === 401) {
						// 如果是 401 错误，跳转到登录页面
						userStore.clearUserData(); // 清除用户数据
						setTimeout(() => {
							uni.redirectTo({
								url: '/pages/login/index',
							});
						}, 1000); // 延迟1秒跳转
					}
					reject(res); // 错误回调
				}
			},
			fail: (err) => {
				reject(err); // 网络错误等失败回调
			},
		});
	});
};

// 文件上传方法
const upload = (url : string, filePath : string, name : string = "file") => {
	const userStore = useUserStore();
	const token = userStore.token;

	return new Promise((resolve, reject) => {
		uni.uploadFile({
			url: `http://localhost:8080/app${url}`,
			filePath,
			name,
			header: {
				Authorization: token ? `Bearer ${token}` : '',
				"Content-Type": "multipart/form-data", // 添加文件上传的 Content-Type
			},
			success: (res) => {
				try {
					const data = JSON.parse(res.data);
					if (data.code === 1 && data) {
						resolve(data);
					} else {
						reject(new Error(`上传失败: ${data.msg || "未知错误"}`));
					}
				} catch (error) {
					console.error("JSON 解析失败:", res.data);
					reject(new Error("服务器返回格式错误"));
				}
			}
			,
			fail: (err) => {
				console.error("上传失败:", err);
				reject(new Error("网络错误或服务器无响应"));
			},
		});
	});
};




const service = {
	get(url : string, params : any = {}) {
		return request(url, "GET", params);
	},
	post(url : string, data : any = {}) {
		return request(url, "POST", data);
	},
	put(url : string, data : any = {}) {
		return request(url, "PUT", data);
	},
	delete(url : string, params : any = {}) {
		return request(url, "DELETE", params);
	},
	upload, // 新增的文件上传方法
};

// 正确导出 service
export { service };